package com.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.entity.Address;
import com.example.entity.Result;
import com.example.service.AddressService;
import com.example.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 *
 */
@RestController
@RequestMapping("/address")
public class AddressController {
    @Autowired
    AddressService addressService;

    @GetMapping("/selectAll")
    public Result selectAll(HttpServletResponse response) {
        JSONObject jsonObject = addressService.selectAll();
        response.setHeader("Access-Control-Allow-Origin", "*");
        String msg = (String)jsonObject.get("msg");
        if (msg.equals("success")) {
            List<Address> addressNodeList = (List<Address>)jsonObject.get("data");
            return ResultUtil.success(addressNodeList);
        }
        return ResultUtil.error(500, msg);
    }

    @GetMapping("/selectById")
    public Result selectById(HttpServletResponse response, Long id) {
        Address addressNode = addressService.selectById(id);
        response.setHeader("Access-Control-Allow-Origin", "*");
        return ResultUtil.success(addressNode);
    }

    @PostMapping("/deleteById")
    public Result deleteById(HttpServletResponse response, @RequestBody Address address) {
        Boolean flag = addressService.deleteById(address.getId());
        response.setHeader("Access-Control-Allow-Origin", "*");
        if (flag == true) {
            return ResultUtil.success(address);
        }
        return ResultUtil.error(500, "删除失败，因为还存在别的关系");
    }

    @PostMapping("/update")
    public Result update(HttpServletResponse response, @RequestBody Address address) {
        JSONObject jsonObject = addressService.update(address);
        response.setHeader("Access-Control-Allow-Origin", "*");
        String msg = (String)jsonObject.get("msg");
        if (msg.equals("success")) {
            Address addressNode = (Address)jsonObject.get("data");
            return ResultUtil.success(addressNode);
        }
        return ResultUtil.error(500, msg);
    }

    @PostMapping("/insert")
    public Result insert(HttpServletResponse response, @RequestBody Address address) {
        JSONObject jsonObject = addressService.insert(address);
        response.setHeader("Access-Control-Allow-Origin", "*");
        String msg = (String)jsonObject.get("msg");
        if (msg.equals("success")) {
            Address addressNode = (Address)jsonObject.get("data");
            return ResultUtil.success(addressNode);
        }
        return ResultUtil.error(500, msg);
    }
}
